package com.ruoyi.common.utils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.convert.Convert;
import com.ruoyi.common.core.constant.CacheConstants;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.PatternMatchUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;

import javax.servlet.http.HttpServletRequest;

/**
 * 安全服务工具类
 *
 * @author ruoyi
 */
public class SecurityUtils {

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户账号
     */
    public static String getUsername() {
        if (ServletUtils.getRequest() == null) {
            return "";
        }
        String username = ServletUtils.getRequest().getHeader(CacheConstants.DETAILS_USERNAME);
        return ServletUtils.urlDecode(username == null ? "" : username);
    }

    /**
     * 获取用户名称
     */
    public static String getRealName() {
        if (ServletUtils.getRequest() == null) {
            return "";
        }
        String realName = ServletUtils.getRequest().getHeader(CacheConstants.DETAILS_REALNAME);
        return ServletUtils.urlDecode(realName == null ? "" : realName);
    }

    /**
     * 获取用户ID
     */
    public static Long getUserId() {
//        if(ServletUtils.getRequest() == null){
//            return null;
//        }
//        String userId =  ServletUtils.getRequest().getHeader(CacheConstants.DETAILS_USER_ID);
//        if(userId != null){
//            return Convert.toLong(userId);
//        }
//        return null;
        try {
            return getLoginUser().getUserId();
        } catch (Exception e) {
            throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取部门id
     */
    public static Long getDeptId() {
        if (ServletUtils.getRequest() == null) {
            return null;
        }
        String deptId = ServletUtils.getRequest().getHeader(CacheConstants.DETAILS_DEPT_ID);
        if (deptId != null) {
            return Convert.toLong(deptId);
        }
        return null;
    }

    /**
     * 获取部门名称
     */
    public static String getDeptName() {
        if (ServletUtils.getRequest() == null) {
            return "";
        }
        String deptName = ServletUtils.getRequest().getHeader(CacheConstants.DETAILS_DEPT_NAME);
        return ServletUtils.urlDecode(deptName == null ? "" : deptName);
    }

    /**
     * 获取公司id
     */
    public static Long getCompanyId() {
        if (ServletUtils.getRequest() == null) {
            return null;
        }
        String companyId = ServletUtils.getRequest().getHeader(CacheConstants.DETAILS_COMPANY_ID);
        if (companyId != null) {
            return Convert.toLong(companyId);
        }
        return null;
    }

    /**
     * 获取公司名称
     */
    public static String getCompanyName() {
        if (ServletUtils.getRequest() == null) {
            return "";
        }
        String companyName = ServletUtils.getRequest().getHeader(CacheConstants.DETAILS_COMPANY_NAME);
        return ServletUtils.urlDecode(companyName == null ? "" : companyName);
    }

    /**
     * 获取请求token
     */
    public static String getToken() {
        return getToken(ServletUtils.getRequest());
    }

    /**
     * 根据request获取请求token
     */
    public static String getToken(HttpServletRequest request) {
        String token = ServletUtils.getRequest().getHeader(CacheConstants.HEADER);
        if (StringUtils.isNotEmpty(token) && token.startsWith(CacheConstants.TOKEN_PREFIX)) {
            token = token.replace(CacheConstants.TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId) {
        return userId != null && 1L == userId;
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 获取业务线编码
     */
    public static String getBizCode() {
        if (ServletUtils.getRequest() == null) {
            return null;
        }
        return ServletUtils.getRequest().getHeader(CacheConstants.BIZ_HEADER);
    }

}
